<?php namespace Core\Myapp\Event;

class Event
{
    protected $_listeners = array();
    public function fire($name, $arguments = array())
    {
        $listeners = $this->sortListener($this->getListners($name));
        foreach($listeners as $listener) {
            call_user_func_array(array(new $listener->class, $listener->method), $arguments);
        }
    }
    protected function getAllListners()
    {
        return $this->_listeners;
    }
    protected function getListners($event)
    {
        $term = array();
        $listeners = $this->_listeners;
        foreach($listeners as $key=>$value) {
            if($value->name == $event) {
                $term[] = $value;
                unset($this->_listeners[$key]);
            }
        }
        return $term;
    }
    public function addListener($listener)
    {
        $this->_listeners[] = $listener;
    }
    protected function sortListener($listeners = array())
    {
        usort($listeners, array($this, "sortHelper"));
        return $listeners;
    }
    protected function sortHelper($a, $b)
    {
        $al = (int)$a->priority;
        $bl = (int)$b->priority;
        if ($al == $bl) {
            return 0;
        }
        return ($al < $bl) ? -1 : 1;
    }
}
